/**
 * UI工具类
 */
export class UIUtils {
    /**
     * 显示加载状态
     * @param {string} message - 加载提示信息
     * @returns {HTMLElement} - 加载状态元素
     */
    static showLoading(message = '加载中...') {
        const loading = document.createElement('div');
        loading.className = 'loading-overlay';
        loading.innerHTML = `
            <div class="loading-spinner"></div>
            <div class="loading-text">${message}</div>
        `;
        document.body.appendChild(loading);
        return loading;
    }

    /**
     * 隐藏加载状态
     * @param {HTMLElement} loadingElement - 加载状态元素
     */
    static hideLoading(loadingElement) {
        if (loadingElement && loadingElement.parentNode) {
            loadingElement.parentNode.removeChild(loadingElement);
        }
    }

    /**
     * 显示提示消息
     * @param {string} message - 提示信息
     * @param {string} type - 提示类型（success/error/warning）
     * @param {number} duration - 显示时长（毫秒）
     */
    static showToast(message, type = 'success', duration = 3000) {
        const container = document.querySelector('.toast-container') || (() => {
            const div = document.createElement('div');
            div.className = 'toast-container';
            document.body.appendChild(div);
            return div;
        })();

        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.innerHTML = `
            <div class="toast-header">
                <i class="fas ${this._getToastIcon(type)} me-2"></i>
                <strong class="me-auto">${this._getToastTitle(type)}</strong>
                <button type="button" class="btn-close" onclick="this.closest('.toast').remove()"></button>
            </div>
            <div class="toast-body">${message}</div>
        `;

        container.appendChild(toast);
        
        // 自动关闭
        setTimeout(() => {
            if (toast.parentNode) {
                toast.remove();
            }
        }, duration);

        return toast;
    }

    /**
     * 显示确认对话框
     * @param {Object} options - 配置选项
     * @returns {Promise} - 用户选择结果
     */
    static showConfirm({
        title = '确认',
        message = '是否确认执行此操作？',
        type = 'warning',
        confirmText = '确认',
        cancelText = '取消'
    } = {}) {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-dialog-centered modal-confirm ${type}">
                    <div class="modal-content">
                        <div class="modal-header">
                            <div class="icon-box">
                                <i class="fas ${this._getConfirmIcon(type)}"></i>
                            </div>
                            <h4 class="modal-title text-center w-100">${title}</h4>
                        </div>
                        <div class="modal-body text-center">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer justify-content-center">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                ${cancelText}
                            </button>
                            <button type="button" class="btn ${this._getConfirmButtonClass(type)} btn-confirm">
                                ${confirmText}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            
            const modalInstance = new bootstrap.Modal(modal);
            modalInstance.show();

            // 确认按钮事件
            modal.querySelector('.btn-confirm').addEventListener('click', () => {
                modalInstance.hide();
                resolve(true);
            });

            // 取消按钮事件
            modal.querySelector('.btn-secondary').addEventListener('click', () => {
                modalInstance.hide();
                resolve(false);
            });

            // 模态框关闭后清理
            modal.addEventListener('hidden.bs.modal', function () {
                document.body.removeChild(modal);
            });
        });
    }

    /**
     * 表单验证
     * @param {HTMLFormElement} form - 表单元素
     * @returns {boolean} - 验证结果
     */
    static validateForm(form) {
        let isValid = true;
        const inputs = form.querySelectorAll('input, select, textarea');

        inputs.forEach(input => {
            // 移除现有的验证状态
            input.classList.remove('is-invalid');
            const feedback = input.nextElementSibling;
            if (feedback && feedback.classList.contains('invalid-feedback')) {
                feedback.style.display = 'none';
            }

            // 验证必填字段
            if (input.hasAttribute('required') && !input.value.trim()) {
                isValid = false;
                input.classList.add('is-invalid');
                this._showFieldError(input, '此字段不能为空');
            }

            // 验证邮箱格式
            if (input.type === 'email' && input.value) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(input.value)) {
                    isValid = false;
                    input.classList.add('is-invalid');
                    this._showFieldError(input, '请输入有效的邮箱地址');
                }
            }

            // 验证数字
            if (input.type === 'number' && input.value) {
                const min = input.getAttribute('min');
                const max = input.getAttribute('max');
                const value = Number(input.value);

                if (min && value < Number(min)) {
                    isValid = false;
                    input.classList.add('is-invalid');
                    this._showFieldError(input, `最小值为 ${min}`);
                }

                if (max && value > Number(max)) {
                    isValid = false;
                    input.classList.add('is-invalid');
                    this._showFieldError(input, `最大值为 ${max}`);
                }
            }
        });

        return isValid;
    }

    // 私有辅助方法
    static _getToastIcon(type) {
        const icons = {
            success: 'fa-check-circle',
            error: 'fa-times-circle',
            warning: 'fa-exclamation-circle'
        };
        return icons[type] || icons.success;
    }

    static _getToastTitle(type) {
        const titles = {
            success: '成功',
            error: '错误',
            warning: '警告'
        };
        return titles[type] || titles.success;
    }

    static _getConfirmIcon(type) {
        const icons = {
            warning: 'fa-exclamation-triangle',
            delete: 'fa-trash-alt',
            info: 'fa-info-circle'
        };
        return icons[type] || icons.warning;
    }

    static _getConfirmButtonClass(type) {
        const classes = {
            warning: 'btn-warning',
            delete: 'btn-danger',
            info: 'btn-info'
        };
        return classes[type] || classes.warning;
    }

    static _showFieldError(input, message) {
        let feedback = input.nextElementSibling;
        if (!feedback || !feedback.classList.contains('invalid-feedback')) {
            feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            input.parentNode.insertBefore(feedback, input.nextSibling);
        }
        feedback.textContent = message;
        feedback.style.display = 'block';
    }
} 